package net.loogn.stardust.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by Administrator on 2017/4/6.
 */
public class HttpHelper {
    private static CloseableHttpClient httpClient = HttpClients.createDefault();
    private static CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();


    public static String postJsonToUrl(String url, Object data) throws IOException {
        return postJsonToUrl(url, data, 6000);
    }

    public static String postJsonToUrl(String url, Object data, int timeout) throws IOException {
        String json = null;
        if (data != null) {
            json = JSON.toJSONStringWithDateFormat(data,"yyyy-MM-dd HH:mm:ss.SSS");
        }
        return postJsonToUrl(url, json, timeout);
    }

    public static String postJsonToUrl(String url, String json) throws IOException {
        return postJsonToUrl(url, json, 6000);
    }

    public static String postJsonToUrl(String url, String json, int timeout) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        httpPost.setConfig(requestConfig);

        if (json != null && json.length() > 0) {
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            StringEntity stringEntity = new StringEntity(json, "utf-8");
            httpPost.setEntity(stringEntity);
        }
        CloseableHttpResponse response = httpClient.execute(httpPost);
        String resultJosn = EntityUtils.toString(response.getEntity(), "utf-8");
        return resultJosn;
    }


}
